package com.zydl.f9164m.fragment.sms;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.utils.BleLog;
import com.clj.fastble.utils.HexUtil;
import com.zydl.f9164m.R;
import com.zydl.f9164m.basis.BasisFragment;
import com.zydl.f9164m.basis.Constants;
import com.zydl.f9164m.bean.ParamListData;
import com.zydl.f9164m.util.CountDown;
import com.zydl.f9164m.util.SoftKeyBoardListener;
import com.zydl.f9164m.util.SubstringUtil;
import com.zydl.f9164m.view.PopHandle;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import my.BleUtils;

public class SMSFragment extends BasisFragment {
    private TabLayout mTabLayout;
    private ViewPager mViewPager;
    private List<Fragment> list_fragment;
    private CheckBox smsConfig;
    private EditText smsCenter, smsPwd;
    private SMSAlarmFragment mAlarm;
    private SMSConfigFragment mConfig;

    @BindView(R.id.btn_save)
    Button saveBtn;
    @BindView(R.id.ll_tab_layout)
    LinearLayout tabLayout;
    @BindView(R.id.relative_layout1)
    RelativeLayout relativeLayoutOne;


    //tablayout的标题
    private String[] mTitles = new String[]{"短信报警号码", "短信配置授权号码"};

    private CountDown mCountDownTimer;
    private static final long MAX_TIME = 11 * 1000;
    private StringBuffer saveResult = new StringBuffer();

    ArrayList<ParamListData> submitList = new ArrayList<>();
    private boolean isFinish = false;

    private String atShowString;
    private List<String> numInitView = new ArrayList<>();

    private PopHandle popHandle;

    private int subPosition = 0;
    private Handler submitHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 74:  //settingSave
                    initSettingSaveThred();
                    break;
                case 75:   //submit
                    BleLog.d("aaaaaaaaa==="+submitList.size());
                    isFinish = false;
                    if (subPosition < submitList.size()) {
                        submit(submitList.get(subPosition));
                        subPosition++;
                    } else {
                        BleUtils.stopNotify();
                        isFinish = true;
                        dismissProgress();
                        mCountDownTimer.cancel();
                        if (!TextUtils.isEmpty(saveResult.toString())) {
                            if (popHandle == null) {
                                popHandle = new PopHandle(mContext, "tips_fail", "错误信息", saveResult.toString());
                            }
                            popHandle.show();
                        } else {
                            showToast("保存成功");
                        }
                    }
                    break;
                case 76:        // //检查是否传输完毕
                    try {
                        if (!isFinish && !getActivity().isFinishing()) {
                            showToast("设置超时，请重试");
                            dismissProgress();
                            BleUtils.stopNotify();
                        }
                    } catch (NullPointerException e) {
                        throw e;
                    }
                    break;
                case 79:
                    BleUtils.stopNotify();
                    isFinish = true;
                    dismissProgress();
                    mCountDownTimer.cancel();
                    break;
            }
        }
    };

    static SMSFragment fragment;

    public static SMSFragment newInstance() {
        if (fragment == null) {
            fragment = new SMSFragment();
        }
        return fragment;
    }

    @Override
    public void initViews() {
        super.initViews();
        setContentView(R.layout.fragment_sm);

        smsConfig = (CheckBox) findViewById(R.id.smsConfig);
        smsCenter = (EditText) findViewById(R.id.sms_center);
        smsPwd = (EditText) findViewById(R.id.sms_pwd);
        mTabLayout = (TabLayout) findViewById(R.id.id_tablayout);
        mViewPager = (ViewPager) findViewById(R.id.id_viewpager);
        mAlarm = new SMSAlarmFragment();
        mConfig = new SMSConfigFragment();
        list_fragment = new ArrayList<>();
        list_fragment.add(mAlarm);
        list_fragment.add(mConfig);
        initEven();
        initCountDownTimer();
        SoftKeyBoardListener.setListener(mContext, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
                relativeLayoutOne.setVisibility(View.GONE);
                tabLayout.setVisibility(View.GONE);
                saveBtn.setVisibility(View.GONE);
            }

            @Override
            public void keyBoardHide(int height) {
                relativeLayoutOne.setVisibility(View.VISIBLE);
                tabLayout.setVisibility(View.VISIBLE);
                saveBtn.setVisibility(View.VISIBLE);
            }
        });
    }

    public void initEven() {
        //viewPager通过适配器与fragment关联
        mViewPager.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return list_fragment.get(position);
            }

            @Override
            public int getCount() {
                return list_fragment.size();
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return mTitles[position];
            }
        });
        //TabLayout和ViewPager的关联
        mTabLayout.setupWithViewPager(mViewPager);
    }

    public void initCountDownTimer() {
        mCountDownTimer = new CountDown();
        mCountDownTimer.setMillisInFuture(MAX_TIME);
        mCountDownTimer.setCountdownInterval(1000);
        mCountDownTimer.setCountDownListener(new CountDown.CountDownListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onFinish() {
                submitHandler.sendEmptyMessage(Constants.CHECK_FINISH);
                //这时候可以做30秒的计时操作
            }

            @Override
            public void onTick(long millisUntilFinished) {

            }
        });
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
    }

    @OnClick(R.id.btn_save)
    public void save() {
        final StringBuffer atShowResult = new StringBuffer();
        submitList.clear();
        saveResult.setLength(0);
        showLoading();
        BleUtils.notify(mContext,new BleNotifyCallback() {
            @Override
            public void onNotifySuccess() {
                subPosition = 0;
                submitHandler.sendEmptyMessage(Constants.SETSAVE);
            }

            @Override
            public void onNotifyFailure(BleException exception) {
                BleLog.d("下发设置打开通知操作失败");
            }

            @Override
            public void onNotifyFailure(String message) {
                showToast(message);
                dismissProgress();
            }

            @Override
            public void onCharacteristicChanged(byte[] data) {
                for (Byte a : data) {
                    atShowResult.append(String.format("%02X", a));
                }
                String sMes = HexUtil.hexStringToString(atShowResult.toString());
                if (sMes.contains("OK")) {
                    atShowResult.setLength(0);
                    submitHandler.sendEmptyMessage(Constants.SUBMIT);
                }else if(sMes.contains("ERROR")){
                    atShowResult.setLength(0);
                    onError();
                }
            }

            @Override
            public void onError() {
                BleLog.d("aaaaaaa===保存失败=="+curDataName);
                saveResult.append(submitList.get(subPosition - 1).getName() + "保存失败" + "\r\n");
            }

            @Override
            public void onReconSuc(String message) {
                dismissProgress();
                showToast(message);
            }
        });

    }

    public void setList(String atShowString) {
        numInitView.clear();
        this.atShowString = atShowString;
        initAtShow(atShowString);
    }

    private void initAtShow(String sMsgObjString) {
        submitList.clear();
        if (sMsgObjString != null && sMsgObjString.trim().length() > 0) {
            String sms_center = SubstringUtil.subString(sMsgObjString, "SMS Center:");
            smsCenter.setText(sms_center);

            String sSMS_Config = SubstringUtil.subString(sMsgObjString, "SMS Config:");
            if (!TextUtils.isEmpty(sSMS_Config) && !sSMS_Config.equals("数据异常，请重新获取")) {
                String[] splitSMS_Config = sSMS_Config.split(";");
                if (4 == splitSMS_Config.length) {
                    String sConfigFlag = splitSMS_Config[0];
                    String sConfigPwd = splitSMS_Config[1];
                    String sConfigNumSize = splitSMS_Config[2];
                    String sConfigPhone = splitSMS_Config[3];
                    smsPwd.setText(sConfigPwd);
                    String[] arrConfigSmsText = sConfigPhone.split(",");
                    mConfig.readData(arrConfigSmsText);
                    smsConfig.setChecked(((sConfigFlag.equals("1")) ? true : false));
                } else if (3 == splitSMS_Config.length) {
                    String sConfigFlag = splitSMS_Config[0];
                    String sConfigPwd = splitSMS_Config[1];
                    String sConfigNumSize = splitSMS_Config[2];
                    if (sConfigNumSize.equals("0")) {
                        String[] arrConfigSmsText =
                                new String[]{"", "", "", "", "", "", "", "", "", ""};
//                        String[] arrConfigSmsText =
//                                new String[]{"", "", "", "", ""};
                        mConfig.readData(arrConfigSmsText);
                    }
                    smsPwd.setText(sConfigPwd);
                    smsConfig.setChecked(((sConfigFlag.equals("1")) ? true : false));
                }else {
                    String[] arrConfigSmsText =
                            new String[]{"", "", "", "", "", "", "", "", "", ""};
                        mConfig.readData(arrConfigSmsText);
                    smsPwd.setText("");
                    smsConfig.setChecked(false);
                }
            }

            //把查找出来的告警列表传过去
            //Alarm Tel Info:
            int iIndexAlarm_tel = sMsgObjString.indexOf("Alarm Tel Info:");
            if (iIndexAlarm_tel != -1) {
                int iIndeAlarm_tel_line = sMsgObjString.indexOf("\r", iIndexAlarm_tel + 15);
                String sAlarm_tel = sMsgObjString.substring(iIndexAlarm_tel + 15, iIndeAlarm_tel_line + 15);
                int iRe_coon = sAlarm_tel.indexOf("Re conn Int:");
                sAlarm_tel = sAlarm_tel.substring(0, iRe_coon);
                System.out.println("sAlarm_tel======== " + sAlarm_tel);
                if (sAlarm_tel.startsWith("Alarm Tel Info")) {
                    String[] arrAlarmSmsText =
                            new String[]{"", "", "", "", ""};

                    mAlarm.readData(arrAlarmSmsText);
                } else if (sAlarm_tel == null || sAlarm_tel.trim().length() == 0) {
                    String[] arrAlarmSmsText =
                            new String[]{"", "", "", "", ""};

                    mAlarm.readData(arrAlarmSmsText);
                } else {
                    String[] arrAlarmSmsText = sAlarm_tel.split(",");
                    mAlarm.readData(arrAlarmSmsText);
                }
            }

        }
    }


    public void initSettingSaveThred() {
//        StringBuffer sb = new StringBuffer();
        boolean bSmsConfigs = smsConfig.isChecked();
        String smsCenters = smsCenter.getText().toString();
        final String smsPwds = smsPwd.getText().toString();

        if (bSmsConfigs) {
            if (smsPwds == null || smsPwds.trim().length() == 0) {
                Toast.makeText(getActivity(), "短信密码不能为空", Toast.LENGTH_LONG).show();
                dismissProgress();
                return;
            }
            if (smsPwds.trim().length() < 6) {
                Toast.makeText(getActivity(), "短信密码固定6位", Toast.LENGTH_LONG).show();
                dismissProgress();
                return;
            }
        }

        if (!TextUtils.isEmpty(smsCenters)) {
            if (smsCenters.length() > 19) {
                Toast.makeText(getActivity(), "短信中心号最长19位", Toast.LENGTH_LONG).show();
                dismissProgress();
                return;
            }
            submitList.add(new ParamListData("短信中心号码", HexUtil.strToHex("AT+SMSCEN=" + smsCenters), "AT+SMSCEN"));
        }


        String[] arrAlarmSmsText = mAlarm.saveData();
        String sArrAlarmSmsTex = "";
        for (int i = 0; i < arrAlarmSmsText.length; i++) {
            sArrAlarmSmsTex = sArrAlarmSmsTex + arrAlarmSmsText[i] + ",";
        }
//        sb.append(HexUtil.strToHex("AT+ATEL=" + sArrAlarmSmsTex ));
        submitList.add(new ParamListData("短信报警号码", HexUtil.strToHex("AT+ATEL=" + sArrAlarmSmsTex), "AT+ATEL"));

            String[] arrConfigSmsText = mConfig.saveData();
            String sArrConfigSmsText = "";
            int iConfigSmsSize = 0;
            for (int i = 0; i < arrConfigSmsText.length; i++) {
                if (arrConfigSmsText[i] != null && arrConfigSmsText[i].trim().length() > 0) {
                    sArrConfigSmsText = sArrConfigSmsText + arrConfigSmsText[i] + ",";
                    iConfigSmsSize += 1;
                }
            }
            if (sArrConfigSmsText.trim().length() > 0) {
                sArrConfigSmsText = sArrConfigSmsText.substring(0, sArrConfigSmsText.length() - 1);
            }
             String smscfg;
            if(bSmsConfigs){
                smscfg = "AT+SMSCFG=1;";
                smscfg += smsPwds + ";" + iConfigSmsSize + ";" + sArrConfigSmsText;
            }else {
                smscfg = "AT+SMSCFG=0";
            }

            submitList.add(new ParamListData("短信配置功能设置", HexUtil.strToHex(smscfg), "AT+SMSCFG"));




//                BleUtils.setMtu(200, new BleMtuChangedCallback() {
//                    @Override
//                    public void onSetMTUFailure(BleException exception) {
//
//                        showToast("设置最大传输失败请重新提交");
//                        dismissProgress();
//                        addSubmit(false,bSmsConfigs,ssampBaseValue);
//
//                    }
//
//                    @Override
//                    public void onMtuChanged(int mtu) {
//                        addSubmit(true,bSmsConfigs,ssampBaseValue);
//                    }
//                });
        submitHandler.sendEmptyMessage(Constants.SUBMIT);
    }

    private void addSubmit(boolean a,boolean bSmsConfigs,String ssampBaseValue){
        if(a){

        }
    }


    private String curDataName;

    private void submit(final ParamListData terminalData) {
        curDataName = terminalData.getName();
        BleLog.d("aaaaaaa===curDataName=="+curDataName);
        BleUtils.write(terminalData.getValue(), new BleWriteCallback() {
            @Override
            public void onWriteSuccess(final int current, final int total, final byte[] justWrite) {

                if (current == total) {
                    mCountDownTimer.start();
                }
            }

            @Override
            public void onWriteFailure(final BleException exception) {
                BleLog.d("aaaaaaa===下发失败=="+curDataName);
                showToast("提交失败，请重试");
                submitHandler.sendEmptyMessage(Constants.END);
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        submitHandler.removeCallbacksAndMessages(null);
    }
}
